//
//  CK_MenuViewController.m
//  MenuDemo
//
//  Created by 陈凯 on 16/4/14.
//  Copyright © 2016年 鸥！陈凯. All rights reserved.
//

#import "CK_MenuViewController.h"
#import "YQLoginViewController.h"
#import "YQUserInfoManager.h"
//#import "CK_LeftViewController.h"
// 抽屉展开的程度
#define kMenuLeftWidth [UIScreen mainScreen].bounds.size.width * 0.7

@interface CK_MenuViewController ()<UITableViewDataSource, UITableViewDelegate,UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

// 默认左侧tableView
@property (nonatomic, strong) UITableView *leftTableView;

@end

@implementation CK_MenuViewController
// 判断当前是否展开
- (BOOL)isShowing {
    if (self.centerViewController.view.transform.tx > 0) {
        return YES;
    }
    return NO;
}
// 初始化方法
static CK_MenuViewController *CK_menuVC = nil;
+ (instancetype)instanceWithLeftViewController:(UIViewController *)leftVC CenterViewController:(UIViewController *)centerVC {
    @synchronized(self) {
        if (!CK_menuVC) {
            
            CK_menuVC = [[CK_MenuViewController alloc]init];
            // 设置window的rootViewController
            [UIApplication sharedApplication].keyWindow.rootViewController = CK_menuVC;
            // 设置属性
            CK_menuVC.leftViewController = leftVC;
            
            CK_menuVC.centerViewController = centerVC;
//           CK_menuVC.centerViewController.navigationController.navigationBar.translucent = NO;
            // 添加子视图控制器和子视图
            if (leftVC) {
                [CK_menuVC addChildViewController:leftVC];
                [CK_menuVC.view addSubview:leftVC.view];
            }else {
                [CK_menuVC setupLeftViewController];
            }
            if (centerVC) {
                [CK_menuVC addChildViewController:centerVC];
                [CK_menuVC.view addSubview:centerVC.view];
            }
        }
    }
    return CK_menuVC;
}
// 默认的菜单视图
- (void)setupLeftViewController {
    self.leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(-kMenuLeftWidth, 0, kMenuLeftWidth, self.view.frame.size.height) style:UITableViewStylePlain];
    // 设置数据源
    self.leftTableView.dataSource = self;
    // 代理
    self.leftTableView.delegate = self;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(-kMenuLeftWidth, 0, kMenuLeftWidth, 150)];
    
    UIImage *image = [UIImage imageNamed:@"头像.jpg"];
    UIImageView *heardView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 40, kMenuLeftWidth - 200, 80)];
    
    heardView.image = image;
    heardView.tag = 2001;
    heardView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [heardView addGestureRecognizer:tap];
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(kMenuLeftWidth - 200 + 40, 60, 150, 40)];
    lable.tag = 2000;
    lable.text = @"未登录";
    lable.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapNameLableAction:)];
    [lable addGestureRecognizer:tap2];
    lable.textColor = [UIColor redColor];
    [view addSubview:lable];
    [view addSubview:heardView];
    self.leftTableView.tableHeaderView = view;
    self.leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.leftTableView.backgroundColor = [UIColor brownColor];
    [self.view addSubview:self.leftTableView];
}
- (void)viewWillAppear:(BOOL)animated
{
    UILabel *lable = [self.view viewWithTag:2000];
    UIImageView *imageView = [self.view viewWithTag:2001];
    if ([[YQUserInfoManager shareManager] uname]) {
        lable.text = [[YQUserInfoManager shareManager] uname];
        [imageView sd_setImageWithURL:[NSURL URLWithString:[[YQUserInfoManager shareManager] coverimg]] placeholderImage:[UIImage imageNamed:@"头像.jpg"]];
        lable.userInteractionEnabled = NO;
        [self.leftTableView reloadData];
    }
    
    
    
}
- (void)tapNameLableAction:(UITapGestureRecognizer *)tap
{
    //模态出登录界面
    YQLoginViewController *loginVc = [YQLoginViewController new];
    UINavigationController *naVC = [[UINavigationController alloc]initWithRootViewController:loginVc];
//    loginVc.userBlock = ^(NSString *name,NSString *coverimg) {
//        UILabel *lable = [self.view viewWithTag:2000];
//        UIImageView *imageView = [self.view viewWithTag:2001];
//        lable.text = [[YQUserInfoManager shareManager] uname];
//        [imageView sd_setImageWithURL:[NSURL URLWithString:[[YQUserInfoManager shareManager] coverimg]] placeholderImage:[UIImage imageNamed:@"头像.jpg"]];
//            lable.userInteractionEnabled = NO;
    
    
//    };
    [self presentViewController:naVC animated:YES completion:nil];
    loginVc.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction:)];
}
- (void)cancelAction:(UIBarButtonItem *)item
{
     [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)tapAction:(UITapGestureRecognizer *)tap
{
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请你选择要打开的图库" preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:picker animated:YES completion:nil];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
//
//    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//    picker.allowsImageEditing = YES;
//    [self presentViewController:picker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
#warning 点击图片后要把图片给头像用   用户信息单例
    UIImageView *imageView = [self.view viewWithTag:2001];
    
//    NSData *data = [NSData dataWithContentsOfFile:info[@"UIImagePickerControllerReferenceURL"]];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        imageView.image = info[@"UIImagePickerControllerOriginalImage"];
        
        [self.leftTableView reloadData];
         [self dismissViewControllerAnimated:YES completion:nil];
    });
     //用户的头像
     NSLog(@"%@",info);
   
}
#pragma mark - UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
// 数据源代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.menuArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuserID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuserID];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuserID];
    }
    cell.textLabel.text = self.menuArray[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    
    return cell;
}
// menuArray的setter方法
- (void)setMenuArray:(NSMutableArray *)menuArray {
    if (_menuArray != menuArray) {
        _menuArray  = nil;
        _menuArray  = menuArray;
        [self.leftTableView reloadData];
    }
}

#pragma mark - UITableViewDelegate
//
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 代理 传值
    if ([self.menuDelegate respondsToSelector:@selector(didClickMenuIndex:Title:)]) {
        [self.menuDelegate didClickMenuIndex:indexPath.row Title:self.menuArray[indexPath.row]];
    }
    // 关闭抽屉
    [self hideLeftViewController];
}

// 获取抽屉方法
+ (instancetype)getMenuViewController {
    return CK_menuVC;
}

// 展示左侧菜单
- (void)showLeftViewController {
    // 动画展开
    [self showLeftViewController:0.7];
}
- (void)showLeftViewController:(CGFloat)duration{
    [UIView animateWithDuration:duration animations:^{
        self.centerViewController.view.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
        self.leftViewController.view.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
        self.leftTableView.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
    }];

}
// 关闭左侧菜单
- (void)hideLeftViewController {
    [self hideLeftViewController:0.7];
}
- (void)hideLeftViewController:(CGFloat)duration {
    // 动画关闭
    [UIView animateWithDuration:duration animations:^{
        self.centerViewController.view.transform = CGAffineTransformMakeTranslation(0, 0);
        self.leftViewController.view.transform = CGAffineTransformMakeTranslation(0, 0);
        self.leftTableView.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // 手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panMenuWithPanGesture:)];
    [self.view addGestureRecognizer:pan];
    // Do any additional setup after loading the view.
}


// 静态变量保存初始状态
static CGPoint begin;
static CGAffineTransform transform;
- (void)panMenuWithPanGesture:(UIPanGestureRecognizer *)pan {
    
        // 位移量
    CGPoint translatePoint = CGPointZero;
    // 开始手势时的位置
    if (pan.state == UIGestureRecognizerStateBegan) {
        begin = [pan locationInView:self.view];
        transform = self.centerViewController.view.transform;
    }
    // 手势过程中的位置
    if (pan.state == UIGestureRecognizerStateChanged) {
        CGPoint end = [pan locationInView:self.view];
        translatePoint = CGPointMake(end.x - begin.x, 0);
    }
    if (pan.state == UIGestureRecognizerStateCancelled || pan.state == UIGestureRecognizerStateEnded) {
        CGPoint pp = [pan velocityInView:self.view];
        NSLog(@"%f",pp.x);
        if (pp.x < 0) {
            [self hideLeftViewController:0.15];
        }
        else{
            [self showLeftViewController:0.15];
        }
        return;
    }

        // 手势过程中，对视图进行位移
    if(self.centerViewController.view.transform.tx >= 0 && self.centerViewController.view.transform.tx <= kMenuLeftWidth) {
        self.centerViewController.view.transform = CGAffineTransformTranslate(transform, translatePoint.x, 0);
        self.leftViewController.view.transform = CGAffineTransformTranslate(transform, translatePoint.x, 0);
        self.leftTableView.transform = CGAffineTransformTranslate(transform, translatePoint.x, 0);
    }
    
   
}
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    if (section) {
//        <#statements#>
//    }
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
